/* eslint-disable default-case */
import { message, Modal } from 'antd';
import _ from 'lodash';
import router from 'umi/router';
import moment from 'moment';
import {
  getRedEmpList,
  probEmpList,
  redEmpTabNum,
  cancelRedEmp,
  getRedDownloadInfo,
  getUploadProgress,
  getProDetail,
  getFeedback,
  getNameList,
  minusSubmit,
  reasonsLeaving,
  minusList,
  minusValidation,
  minusOver,
  minusUpdate,
  minusUpdateOver,
  getCustnewList,
  uploadFileRedEmp,
  getAdjEndDateInfo,
  getRespUserList,
} from '@/services/customerservicemanage';
import { getDeduAssDetail } from '@/services/redass';
import * as service from '@/services/socket';
import { SocketActions, batchTaskFactory } from '@/models/socket';
import { delay } from '@/utils/dva';

// 非常重要属性
const namespace = 'reducemp';
const ModelAddEmp = {
  namespace,
  state: {
    data: {
      // 列表数据
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    tabList: [
      { itemCode: '1', itemName: '办理中', isHas: false },
      { itemCode: '2', itemName: '已完成', isHas: false },
      { itemCode: '4', itemName: '问题人员', isHas: false },
    ],
    expandForm: false,
    valuesArr: ['empName', 'idCode', 'sendType', 'custId', 'quoId', 'custContId', 'primId','operTime'],
    batchQuery: {
      // 批量上传数据
      sendType: '1',
      insMergeFlag: '1',
      adjFlag: '2',
    },
    activeKey: '1',
    proBaseList: {},
    proFbList: [],
    probId: '',
    nameList: [],
    RemoveRsnList: [], // 离职原因
    minusList: {}, // 减员回显
    deduPdInfoList: [], // 减员回显分项设置
    deduInsInfoList: [],
    minusUpdateList: {}, // 减员修改页回显
    pdInfoList: [], // 减员修改回显分项设置
    custList: [],
    formFieldsValue: {},
    showProgress: false,
    currentStep: 0,
    progressPercent: 0,
    resultInfo: {
      // 结果数据必传
      batchName: '', // 任务名称
      taskCount: 0, // 导入数据
      successCount: 0, // 成功数据
      errorCount: 0, // 失败数据
      batchNo: '', // 批次号
      errorUrl: '/csApi/empSendRemoveService/exportErrorExcel', // 下载错误信息地址
      errorParams: null, // 下载错误数据参数
    },
    batchId: null,
    respUserList: [],
    downloadParams: {}, // 问题人员导出参数
  },
  effects: {
    pageMinusSubmit: [
      /* eslint-disable func-names */
      function*({ payload }, { call }) {
        const validResponse = yield call(minusValidation, payload);
        if (validResponse.success && validResponse.data && validResponse.data.frameFlag) {
          return {
            type: 'minusValidation',
            response: validResponse,
          };
        }
        if (validResponse.success && validResponse.data && !validResponse.data.frameFlag) {
          const overResponse = yield call(minusOver, payload);
          return {
            type: 'minusOver',
            response: overResponse,
          };
        }
        return {
          type: '',
          response: validResponse,
        };
      },
      { type: 'throttle', ms: 5000 },
    ],
    // 获取列表
    fetchList: [
      function*({ payload }, { call, put }) {
        const response = yield call(getRedEmpList, payload);
        const {
          pageArg: { currentPage, pageSize },
        } = payload;
        yield put({
          type: 'getList',
          payload: {
            data: [],
            currentPage,
            pageSize,
          },
        });
        if (response.success) {
          yield put({
            type: 'getList',
            payload: {
              data: response.data,
              currentPage,
              pageSize,
            },
          });
        } else {
          message.warning(`${response.message || '服务端错误！'}`);
        }
      },
      { type: 'takeLatest' },
    ],
    // 减员模态框客户
    *fetchCustnewList({ payload }, { call, put }) {
      const response = yield call(getCustnewList, { name: payload });
      yield put({
        type: 'getCustnewList',
        payload: Array.isArray(response.data) ? response.data : [],
      });
    },
    // 点击减员输入姓名
    *fetchNameList({ payload }, { call, put }) {
      const response = yield call(getNameList, payload);
      if (response.success) {
        yield put({
          type: 'getNameList',
          payload: response.data,
        });
      } else {
        message.warning(response.message || '查询不到该雇员：服务器端错误');
      }
    },
    // 减员模态框确定
    minusSubmit: [
      function*({ payload, callback }, { call }) {
        const response = yield call(minusSubmit, payload);
        if (callback) {
          callback(response);
        }
      },
      { type: 'throttle', ms: 10000 },
    ],
    // 减员回显
    *fetchminusList({ payload }, { call, put }) {
      const response = yield call(minusList, payload);
      if (response.success) {
        yield put({
          type: 'getMinusList',
          payload: response.data,
        });
      } else {
        yield put({
          type: 'updateModelData',
          payload: {
            minusList: {}, // 减员回显
            deduPdInfoList: [], // 减员回显分项设置
            minusUpdateList: {}, // 减员修改页回显
            pdInfoList: [], // 减员修改回显分项设置
            custList: [],
          },
        });
        message.warning(`${response.message || '服务端错误！'}`);
      }
    },
    // 离职原因列表
    *reasonsLeaving({ payload }, { call, put }) {
      const response = yield call(reasonsLeaving, payload);
      if (response.success) {
        yield put({
          type: 'LeavingList',
          payload: response.data,
        });
      }
    },
    // 减员前效验
    *minusValidation({ payload, callback }, { call }) {
      const response = yield call(minusValidation, payload);
      if (callback) {
        callback(response);
      }
    },
    // 减员完成
    *minusOver({ payload, callback }, { call }) {
      const response = yield call(minusOver, payload);
      if (callback) {
        callback(response);
      }
    },
    // 减员修改页回显
    *fetchminusUpdateList({ payload, callback }, { call, put }) {
      const response = yield call(minusUpdate, payload);
      if (response.success) {
        yield put({
          type: 'getMinusUpdateList',
          payload: response.data,
        });
        if (callback) {
          callback(response);
        }
      } else {
        Modal.warning({
          title: response.message || '获取员工信息：服务端错误',
          okText: '知道了',
          onOk: () => {
            router.goBack();
          },
        });
      }
    },
    // 减员修改页提交
    minusUpdateOver: [
      function*({ payload, callback }, { call }) {
        const response = yield call(minusUpdateOver, payload);
        if (callback) {
          callback(response);
        }
      },
      { type: 'throttle', ms: 10000 },
    ],
    // 获取问题人员列表
    *fetchProbList({ payload }, { call, put }) {
      const response = yield call(probEmpList, payload);
      const {
        pageArg: { currentPage, pageSize },
      } = payload;
      yield put({
        type: 'getList',
        payload: {
          data: [],
          currentPage,
          pageSize,
        },
      });
      if (response.success) {
        yield put({
          type: 'getList',
          payload: {
            data: response.data,
            currentPage,
            pageSize,
          },
        });
      } else {
        message.warning(`${response.message || '服务端错误！'}`);
      }
    },

    /**
     * 获取页签数量
     * @param {action} action
     * @param {effects} effects
     * @return {response} response
     */
    *fetchTabNum({ payload }, { call }) {
      const response = yield call(redEmpTabNum, payload.formFieldsValue);
      return response;
    },
    /**
     * 设置激活页签
     * @param {action} action
     * @param {effects} effects
     * @return {string} activeKey
     */
    *setFetchTabNumActiveKey({ payload }, { put, select }) {
      let activeKey = yield select(state => state.reducemp.activeKey);
      const newTabList = yield select(state => state.reducemp.tabList);
      const tabList = _.cloneDeep(newTabList);
      const { data } = payload;

      const sortNumber = (a, b) => a.itemCode - b.itemCode;
      const tabCodeArr = data.sort(sortNumber);
      const isHasBadgeCurrentTab = tabCodeArr.some(item => `${item.status}` === activeKey); // 当前页签有没有查询到
      if (!isHasBadgeCurrentTab) {
        activeKey = `${tabCodeArr[0].status}`;
      }
      tabCodeArr.forEach(item => {
        if (`${item.status}` !== activeKey) {
          if (item.status === 4) {
            tabList[item.status - 2].isHasBadge = true;
          } else {
            tabList[item.status - 1].isHasBadge = true;
          }
        }
      });
      yield put({
        type: 'updateModelData',
        payload: { activeKey, tabList },
      });
      return activeKey;
    },
    *setFetchTabNumFormFieldsValue({ payload }, { put, select }) {
      const activeKey = yield select(state => state.reducemp.activeKey);
      const getListParams = {
        ...payload.formFieldsValue,
        pageArg: { currentPage: payload.currentPage, pageSize: payload.pageSize },
      };
      if (activeKey === '4') {
        if (payload.formFieldsValue) {
          yield put({
            type: 'updateModelData',
            payload: {
              ...payload.formFieldsValue,
            },
          });
        }
        yield put({
          type: 'problempage/getProList',
          payload: {
            ...getListParams,
            busiType: 21,
          },
        });
      } else {
        yield put({
          type: 'fetchList',
          payload: { ...getListParams, taskStatus: activeKey },
        });
      }
    },
    *setFetchTabNumNoResult(action, { put, select }) {
      const activeKey = yield select(state => state.reducemp.activeKey);
      yield put({
        type: 'getList',
        payload: {
          data: {},
          currentPage: 1,
          pageSize: 10,
        },
      });
      if (activeKey === '4') {
        yield put({
          type: 'problempage/updateProList',
          payload: {
            data: [],
            currentPage: 1,
            pageSize: 10,
          },
        });
      }
    },
    // 取消减员
    cancelRedEmp: [
      function*({ payload, callback }, { call }) {
        const response = yield call(cancelRedEmp, payload);
        if (callback) callback(response);
      },
      { type: 'throttle', ms: 10000 },
    ],
    // 获取下载模板fileId fileName
    *getDownloadInfo({ payload }, { call, put }) {
      const response = yield call(getRedDownloadInfo, payload);
      yield put({
        type: 'updateQuery',
        payload,
      });
      if (response.success) {
        const fileInfo = response.data.split('|');
        yield put({
          type: 'publicdata/setFileDownload',
          payload: { fileId: fileInfo[0], fileName: fileInfo[1] },
        });
      }
    },
    // 获取上传进度数据
    *getUploadProgress({ payload, callback }, { call, put }) {
      const response = yield call(getUploadProgress, payload);
      if (response.success) {
        yield put({
          type: 'updateQuery',
          payload: { progressPercent: response.data.successProp },
        });
      }
      if (callback && typeof callback === 'function') {
        callback(response);
      }
    },
    // 获取问题人员详情
    *fetchProDetailList({ payload }, { call, put }) {
      const response = yield call(getProDetail, payload);
      if (response.success) {
        yield put({
          type: 'getProDetail',
          payload: response.data,
        });
      }
    },
    // 问题人员反馈
    *proFeedBack({ payload, callback }, { call }) {
      const response = yield call(getFeedback, payload);
      if (response.success) {
        if (callback) {
          callback(response);
        }
      } else {
        message.warning(`${response.message || '反馈失败'}`);
      }
    },
    // 问题人员反馈并取消标记
    *cancelProbFlag({ payload, callback }, { call }) {
      const response = yield call(getFeedback, payload);
      if (callback) {
        callback(response);
      }
    },
    // 是否可减少险种操作
    fetchAssDetail: [
      function*({ payload }, { call }) {
        const response = yield call(getDeduAssDetail, payload);
        return response;
      },
      { type: 'throttle', ms: 10000 },
    ],
    // 上传文件:批量进度
    uploadFileWithProgress: [
      function*({ payload }, { call, put }) {
        try {
          const response = yield call(uploadFileRedEmp, payload);
          if (response.success) {
            // 不是100表示需要走队列
            if (response.data && response.data.successProp !== 100) {
              const { batchId } = response.data;
              const batchTask = batchTaskFactory(batchId, namespace, 'handleBatchTask');

              yield put.resolve({
                type: `socket/${SocketActions.subSocketChannel}`,
                payload: {
                  batchTask,
                },
              });
              // 订阅成功后再触发进度条
              yield put({
                type: 'updateModelData',
                payload: { showProgress: true },
              });
            } else {
              if (response.data && response.data.successCount) {
                const responseAdjCount = yield call(getAdjEndDateInfo, {
                  batchId: payload.batchId,
                });
                if (responseAdjCount.success && responseAdjCount.data) {
                  response.data = { ...response.data, adjCount: responseAdjCount.data.adjCount };
                } else {
                  message.warning(`${response.message || '获取结束日期调整数据：服务端错误'}`);
                }
              }

              yield put({
                type: 'handleBatchTask',
                payload: response.data,
              });
            }
          } else {
            message.warning(response.message || '上传文件错误：服务器端错误');
          }

          // 无需返回response对象
        } catch (e) {
          console.error(e);
        }
      },
      { type: 'throttle', ms: 10000 },
    ],
    *handleBatchTask({ payload }, { put, select, call }) {
      const state = yield select(s => s.reducemp);
      let { showProgress, resultInfo, currentStep } = state;
      const { batchQuery } = state;
      showProgress = true;

      // 减员成功后查询调整数据
      if (payload.successProp >= 100 && payload.successCount) {
        const responseAdjCount = yield call(getAdjEndDateInfo, {
          batchId: payload.batchId,
        });
        if (responseAdjCount.success && responseAdjCount.data) {
          payload = { ...payload, adjCount: responseAdjCount.data.adjCount };
        } else {
          message.warning(`${responseAdjCount.message || '获取结束日期调整数据：服务端错误'}`);
        }
      }

      if (payload.successProp >= 100) {
        resultInfo.errorParams = {
          batchId: payload.batchId,
          sendType: batchQuery.sendType,
          insMergeFlag: batchQuery.insMergeFlag,
        };
        resultInfo = { ...resultInfo, ...payload };
        currentStep += 1;
        showProgress = false;
        // 先更新进度
        yield put({
          type: 'updateBatchTask',
          payload: {
            progressPercent: payload.successProp,
            resultInfo,
          },
        });
        console.timeEnd('批量减员时间');
        yield delay(3000);
        // 再更新状态
        yield put({
          type: 'updateBatchTask',
          payload: {
            currentStep,
            showProgress,
          },
        });
      } else {
        yield put({
          type: 'updateBatchTask',
          payload: { progressPercent: payload.successProp, resultInfo },
        });
      }
    },
    // 获取所属客服列表
    *fetchRespUserList({ payload }, { call, put }) {
      const response = yield call(getRespUserList, payload);
      yield put({
        type: 'updateModelData',
        payload: {
          respUserList: [],
        },
      });
      if (response.success && response.data) {
        yield put({
          type: 'updateModelData',
          payload: {
            respUserList: Array.isArray(response.data) ? response.data : [],
          },
        });
      } else {
        message.warning(response.message || '获取所属客服数据：服务端错误');
      }
    },
  },

  reducers: {
    // 获取列表
    getList(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list = data.pageRecords && Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        data: {
          list,
          pagination: { total: data.totalCount || 0, current: currentPage, pageSize },
        },
      };
    },
    getCustnewList(state, { payload }) {
      return {
        ...state,
        custList: payload,
      };
    },
    // 点击减员输入姓名
    getNameList(state, { payload }) {
      return {
        ...state,
        nameList: payload,
      };
    },
    // 取消姓名和客户
    cancleList(state) {
      return {
        ...state,
        nameList: [],
        custList: [],
      };
    },
    // 减员回显
    getMinusList(state, { payload }) {
      const deduPdInfoLists = [];
      let newdeduInsInfoList = [];
      if (payload.deduPdInfoList) {
        payload.deduPdInfoList.map(item => {
          deduPdInfoLists.push({
            id: item.pdId,
            name: item.pdName,
            endDate: '',
            pdCate: item.pdCate,
            cityId: item.cityId,
            cityName: item.cityName,
            execType: item.execType,
            execTypeName: item.execTypeName,
          });
          if (item.pdId === 'PDINF_0000000001') {
            // 社保
            newdeduInsInfoList = item.deduInsInfoList;
          }
          return null;
        });
      }
      return {
        ...state,
        minusList: payload,
        deduPdInfoList: deduPdInfoLists,
        deduInsInfoList: newdeduInsInfoList,
      };
    },
    // 减员修改页回显
    getMinusUpdateList(state, { payload }) {
      const pdInfoLists = [];
      if (payload.deduPdInfoList) {
        payload.deduPdInfoList.map(item => {
          pdInfoLists.push({
            id: item.pdId,
            name: item.pdName,
            endDate: item.endDate,
            pdCate: item.pdCate,
            cityId: item.cityId,
            cityName: item.cityName,
            execType: item.execType,
            execTypeName: item.execTypeName,
            lastDay: moment(item.endDate).daysInMonth(),
          });
          return null;
        });
      }
      const deduInsInfoList =
        (payload.deduPdInfoList &&
          payload.deduPdInfoList.length &&
          payload.deduPdInfoList.filter(item => item.pdId === 'PDINF_0000000001')) ||
        [];
      return {
        ...state,
        minusUpdateList: payload,
        deduPdInfoList: pdInfoLists,
        insInfoList:
          (deduInsInfoList.length &&
            JSON.parse(JSON.stringify(deduInsInfoList[0].deduInsInfoList))) ||
          [],
      };
    },
    // 离职原因列表
    LeavingList(state, { payload }) {
      return {
        ...state,
        RemoveRsnList: payload,
      };
    },
    // 更新批量上传参数
    updateQuery(state, { payload }) {
      return {
        ...state,
        batchQuery: { ...state.batchQuery, ...payload },
      };
    },
    // 问题人员详情
    getProDetail(state, { payload }) {
      return {
        ...state,
        proBaseList: payload,
        proFbList: payload.probFdbkList,
        probId: payload.probId,
      };
    },
    // 设置修改当前state数据
    updateModelData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    // 设置页签状态
    updateTabListQuery(state, { payload }) {
      const { tabList } = state;
      tabList.forEach((item, index) => {
        if (item.itemCode === payload.activeKey) {
          tabList[index].isHasBadge = false;
        }
      });
      return {
        ...state,
        tabList,
        ...payload,
      };
    },
    // 更新批量任务数据
    updateBatchTask(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
  subscriptions: {
    socket({ dispatch }) {
      service.listen(async action => {
        // 判断是否自己命名空间的回调
        if (action.namespace === namespace) {
          switch (action.type) {
            case 'task':
              await dispatch({
                type: 'handleBatchTask',
                payload: action.data,
              });
              await dispatch({
                type: `socket/${SocketActions.handleUpdateBatchTask}`,
                payload: {
                  successProp: action.data.successProp,
                  batchId: action.data.batchId,
                },
              });
              // 全局保存
              dispatch({
                type: 'publicdata/updateBatchTaskData',
                payload: action.data,
              });
              break;
          }
        }
      }, namespace);
    },
  },
};

export default ModelAddEmp;
